<?php

class KolSys_MySQLDatabase
{	
	public static function getInstance(){
		return KolSys_Singleton::getInstance(__CLASS__);
	}
	public static function connect()
	{
		global $settings;
		mysql_connect($settings['mysql']['host'],$settings['mysql']['username'],$settings['mysql']['password']);
		mysql_select_db($settings['mysql']['database']);
	}
	public static function getTableFields($table)
	{
		$sql="DESCRIBE $table";
		$rows=MySQLDatabase::fetchAll(mysql_query($sql));
		$fields=array();
		foreach($rows as $row)
		{
			$fields[]=$row['Field'];
		}
		return $fields;
	}
	public static function fetchAll($r)
	{
		$rows=array();
		while($row=mysql_fetch_assoc($r))
		{
			$rows[]=$row;
		}
		return $rows;
	}

	public static function query($sql)
	{
		if($result=mysql_query($sql))
		{
			return $result;
		}else{
			$errorText="\$sql:$sql\n<br>\n".mysql_error();
			die($errorText);
		}
	}

	public static function free_result($result)
	{
		if(is_resource($result))
		{
			mysql_free_result($result);
		}
	}

	public static function getDBCookie()
	{
		global $settings;
		$u=mysql_real_escape_string($settings['kol']['username']);
		
		//See if the cookie exists, if not create a blank one
		$result=mysql_query("SELECT * FROM `cookies`WHERE username='$u';") or die(mysql_error());
		if(!mysql_num_rows($result)){
			self::free_result($result);
			$result=mysql_query("INSERT INTO `cookies` (`cookie`,`timestamp`,`username`) VALUES('',CURRENT_TIMESTAMP,'$u');") or die(mysql_error());
			self::free_result($result);
		}

		$result=mysql_query("SELECT * FROM `cookies`WHERE username='$u';") or die(mysql_error());
		$r=mysql_fetch_assoc($result);
		self::free_result($result);
		return $r['cookie'];

	}

	public static function setDBCookie($value){
		global $settings;
		$u=mysql_real_escape_string($settings['kol']['username']);
		$v=mysql_real_escape_string($value);
		$result=mysql_query("SELECT * FROM `cookies`WHERE username='$u';") or die(mysql_error());
		if(mysql_num_rows($result)){
			self::free_result($result);
			$result=mysql_query("UPDATE `cookies`SET `cookie`='$v',`timestamp`= CURRENT_TIMESTAMP WHERE username='$u';") or die(mysql_error());
		}else{
			self::free_result($result);
			$result=mysql_query("INSERT INTO `cookies` (`cookie`,`timestamp`,`username`) VALUES('$v',CURRENT_TIMESTAMP,'$u');") or die(mysql_error());			
		}
		self::free_result($result);
	}

	public static function sprintf_escape()
	{
		$args=func_get_args();
		$sql=array_shift($args);
		return vsprintf($sql, array_map('mysql_real_escape_string',$args)); 
	}


	public static function getVariables()
	{
		global $settings;
		$query="SELECT * FROM `variables` WHERE `username`='%s' LIMIT 1";
		$sql=self::sprintf_escape($query,$settings['kol']['username']);
		$result=self::query($sql);
		if(mysql_num_rows($result)>0)
		{
			$row=mysql_fetch_assoc($result);
			self::free_result($result);
			return $row;
		}else{
			self::free_result($result);
			return false;
		}
	}

	public static function escapeKeys($keys)
	{	
		$dbKeys=array();
		foreach($keys as $key)
		{
			$dbKeys[]='`'.mysql_real_escape_string($key).'`';
		}
		return $dbKeys;
	}

	public static function escapeValues($values)
	{	
		$dbValues=array();
		foreach($values as $value)
		{
			$dbValues[]="'".mysql_real_escape_string($value)."'";
		}
		return $dbValues;
	}

	public static function escapeSets($associativeArray)
	{
		$setsArray=array();
		foreach($associativeArray as $key=>$value)
		{
			$k=mysql_real_escape_string($key);
			$v=mysql_real_escape_string($value);
			$setsArray[]="`$k`='$v'";
		}
		return $setsArray;
	}
	public static function setVariables($setArray)
	{
		global $settings;
		if(!sizeof($setArray))
		{
			die('Empty array sent to setVariables!');
		}
		if(!isset($setArray['username'])){$setArray['username']=$settings['kol']['username'];}
		if(self::getVariables()==false)
		{
			$keys=implode(',',self::escapeKeys(array_keys($setArray)));
			$values=implode(',',self::escapeValues(array_values($setArray)));
			$sql="INSERT INTO `variables` ($keys) VALUES($values)";
			$result=self::query($sql);
			self::free_result($result);
		}else{
			$sets=implode(',',self::escapeSets($setArray));
			$query="UPDATE `variables` SET $sets WHERE `username`='%s' LIMIT 1";
			$sql=self::sprintf_escape($query,$settings['kol']['username']);
			$result=self::query($sql);
			self::free_result($result);
		}
	}

	public static function getLastSeen()
	{
		$vars=self::getVariables();
		if($vars!=false)
		{
			return $vars['lastseen'];
		}else{
			return false;
		}
	}

	public static function setLastSeen($value)
	{
		$vars=array('lastseen'=>$value);
		self::setVariables($vars);
	}

	public static function setMainLoop($value)
	{
		$vars=array('mainloop'=>$value);
		self::setVariables($vars);
	}

	public static function getMainLoop()
	{
		$vars=self::getVariables();
		if($vars!=false)
		{
			return $vars['mainloop'];
		}else{
			return 'N';
		}
	}
	
}